package com.sudo.controller;

import com.sudo.common.enums.UserParams;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.MapUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：为道日损 2020-04-24 15:29
 */
public class BaseController {

    String getSessionUser(HttpServletRequest request) {
        return request.getHeader(UserParams.HEADER_USER_ID.value);
    }

    boolean superName(String username) {
        return UserParams.SUPER_NAME.value.equals(username);
    }
    boolean superAdmin(String roleCode) {
        return UserParams.SUPER_ADMIN.value.equals(roleCode);
    }

    /**
     * 禁止删除的菜单
     */
    final static String[] DONT_DEL_MENUS = {
            "0000",
            "sysRun",
            "roleRun",
            "menuRun",
            "dictRun",
            "userRun",
            "roleAuth",
            "btnConf",
            "sysLogs",
            "user_behavior",
            "user_loginRecord",
            "fileRun",
            "upload_file",
            "myFiles",
            "allFiles"
    };

    boolean superMenu(String menuCode) {
        return Arrays.asList(DONT_DEL_MENUS).contains(menuCode);
    }

    protected Map<String, String> getErrors(BindingResult result) {
        List<FieldError> errorList = result.getFieldErrors();
        Map<String, String> map = new HashMap<>();
        for (FieldError error : errorList) {
            //发生验证错误所对应的某一个属性
            String errorFiled = error.getField();
            //验证错误信息
            String errorMsg = error.getDefaultMessage();
            map.put(errorFiled, errorMsg);
        }
        return map;
    }

    String getFirstError(BindingResult result) {
        Map<String, Object> map = result.getModel();
        Object o = MapUtil.getFirstValueOrNull(map);
        Field[] fields = o.getClass().getDeclaredFields();

        for (Field field : fields) {
            FieldError fieldError = result.getFieldError(field.getName());
            if (null != fieldError) {
                return fieldError.getDefaultMessage();
            }
        }
        return null;
    }
}
